package ke03.pm;

import java.io.*;
import java.util.Vector;

public class MiniDatenbank implements Database {

	File file;

	public MiniDatenbank(File file) {
		this.file = file;
	}

	@Override
	public boolean write(int key, Vector<?> v) {
		if (key == 0) {
			return false;
		}
		Vector<?> check = read(key);
		if (check != null) {
			return false;
		}
		String csvString = csvBuilder(key, v);
		BufferedWriter bufWriter = null;
		try {
			bufWriter = new BufferedWriter(new FileWriter(file, true));
			bufWriter.write(csvString);
			bufWriter.newLine();
			return true;
		} catch (IOException e) {
			return false;
		} finally {
			try {
				if (bufWriter != null) {
					bufWriter.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public String csvBuilder(int key, Vector<?> v) {
		StringBuffer buffer = new StringBuffer();
		buffer.append(key);
		buffer.append(";");
		for (int i = 0; i < v.size(); i++) {
			buffer.append(v.elementAt(i)).append(";");
		}
		return buffer.toString();
	}

	@Override
	public Vector<?> read(int key) {
		FileReader reader = null;
		try {
			reader = new FileReader(file);
			BufferedReader bufReader = new BufferedReader(reader);
			String row;
			while ((row = bufReader.readLine()) != null) {
				if (row.startsWith("" + key + ";")) {
					Vector<?> v = vectorBuilder(row);
					return v;
				}
			}
		} catch (IOException e) {
			return null;
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	public Vector<?> vectorBuilder(String row) {
		Vector<String> v = new Vector<String>();
		String[] eintraege = row.split(";");
		for (int i = 1; i < eintraege.length; i++) {
			v.add(eintraege[i]);
		}
		return v;
	}

	@Override
	public boolean drop() {
		if (file.exists() && file.isFile()) {
			return file.delete();
		}
		return true;
	}

	@Override
	public boolean delete(int key) {
		RandomAccessFile f = null;
		String zeile = "";
		try {
			f = new RandomAccessFile(file, "rw");
			boolean weiter = true;
			while (weiter) {
				long pointer = f.getFilePointer();
				zeile = f.readLine();
				if (zeile != null) {
					if (zeile.startsWith("" + key + ";")) {
						f.seek(pointer);
						for (int i = 0; i < String.valueOf(key).length(); i++) {
							f.writeBytes("0");
						}
						weiter = false;
					}
				} else {
					weiter = false;
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				f.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return (zeile != null);
	}
}
